#include "../include/head.h"

void *pthread_enter(void *arg)
{
    shareRes_t *share = (shareRes_t *)arg;
    

    Client_info* client_info = share->pclient_info;
    pthread_mutex_t* mtx_clientInfo = share->mutex_client_info;
    pthread_mutex_t* mtx_taskQueue = share->mutex_taskqueue;
    pthread_cond_t* cond_taskQueue = share->cond;
    taskQueue_t* taskQueue = share->taskqueue;
    pthread_mutex_t *mysql_mutex = share->mysql_mutex;
    int *epfd = share->epfd;
    int *exitFlag = share->exitflag;

    // MYSQL连接
    pthread_mutex_lock(mysql_mutex);
    MYSQL *mysql2 = mysql_init(NULL);
    /* MYSQL *connect_ret2 = mysql_real_connect(mysql2, "localhost", "root", "031178514530", "user_base", 0, NULL, 0); */
    MYSQL *connect_ret2 = mysql_real_connect(mysql2, "localhost", "admin", "123", "user_base", 0, NULL, 0);
    /* MYSQL *connect_ret2 = mysql_real_connect(mysql2, "localhost", "admin", "210710", "user_base", 0, NULL, 0); */
    if(connect_ret2 == NULL)
    {
        fprintf(stderr, "%s:%s\n", "mysql connect", mysql_error(connect_ret2));
        exit(-1);
    }
    pthread_mutex_unlock(mysql_mutex);

    while(1)
    {
        pthread_mutex_lock(mtx_taskQueue);

        while(*exitFlag != 1 && taskQueue->queuesize==0)
        {
            pthread_cond_wait(cond_taskQueue,mtx_taskQueue);
        }
        if(*exitFlag == 1)
        {
            pthread_mutex_unlock(mtx_taskQueue);
            pthread_exit(NULL);
        }

        taskNode_t* node = head_delete(taskQueue);
        // printf("拿到结点！\n");

        pthread_mutex_unlock(mtx_taskQueue);

        // 检查是否是过时包
        //pthread_mutex_lock(mtx_clientInfo);

        // int user_id;
        // if(node->type==C_OP_GETS_BEGIN||node->type==C_OP_PUTS_BEGIN)
        // {
        //     user_id = client_info[node->father_netfd].belongs_to_userid;
        // }
        // else
        // {
        //     user_id = client_info[node->netfd].belongs_to_userid;
        // }
        // printf("user_id == %d \n node->user_id = %d\n",user_id,node->user_id);
        // if (user_id == -1 || user_id != node->user_id)
        // {
        //     printf("丢弃结点！\n");
        //     pthread_mutex_unlock(mtx_clientInfo);
        //     free(node);
        //     continue;
        // }
        //pthread_mutex_unlock(mtx_clientInfo);

        // printf("node_type:%d\n", node->type);
        pthread_func(node, mtx_clientInfo, mysql2, epfd, client_info);

        free(node);
    }
}
